package com.lizard.schedule.persistence.db;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.lizard.schedule.persistence.db.table.DownloadFileInfoTbl;
import com.lizard.schedule.persistence.db.table.DownloadThreadInfoTbl;
import com.lizard.schedule.persistence.db.table.ScheduleVersionTbl;
import com.lizard.schedule.ScheduleApplication;
import com.lizard.schedule.persistence.db.table.IdGeneratorTbl;
import com.lizard.schedule.persistence.db.table.ScheduleTbl;

/**
 * 数据库帮助类
 */
public class DbHelper extends SQLiteOpenHelper {

    private static DbHelper dbHelper;

    /**
     * 数据库名
     */
    private static final String DB_NAME = "schedule_db";

    /**
     * 版本
     */
    private static int DB_VERSION = 13;

    private SQLiteDatabase mSqLiteDatabase;

    private DbHelper() {
        super(ScheduleApplication.applicationContext, DB_NAME, null, DB_VERSION);
        mSqLiteDatabase = getWritableDatabase();
    }

    public static DbHelper getInstance() {
        if (dbHelper == null) {
            synchronized (DbHelper.class) {
                if (dbHelper == null) {
                    dbHelper = new DbHelper();
                }
            }
        }
        return dbHelper;
    }

    /**
     * 数据库操作时需要的SqliteDatabase类由此获取
     *
     * @return
     */
    public SQLiteDatabase getSqliteDatabase() {
        return mSqLiteDatabase;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        ScheduleTbl.getInstance().createTbl(null, db);
        ScheduleVersionTbl.getInstacne().createTbl(db);
        IdGeneratorTbl.getInstance().createTbl(db);
        DownloadThreadInfoTbl.getInstance().createTbl(db);
        DownloadFileInfoTbl.getInstance().createTbl(db);
    }

    /**
     * 删除所有表
     * @param db
     */
    private void dropAllTbls(SQLiteDatabase db){
        ScheduleTbl.getInstance().dropTbl(db);
        ScheduleVersionTbl.getInstacne().dropTbl(db);
        IdGeneratorTbl.getInstance().dropTbl(db);
        DownloadThreadInfoTbl.getInstance().dropTbl(db);
        DownloadFileInfoTbl.getInstance().dropTbl(db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if(oldVersion < newVersion){    // 升级 策略：一级一级更新表
            if(oldVersion < 11){
                DownloadThreadInfoTbl.getInstance().createTbl(db);
                DownloadFileInfoTbl.getInstance().createTbl(db);
            }

            if(oldVersion < 12){
                // 增加是否支持断点续传字段
                DownloadFileInfoTbl.getInstance().addColumnSupportRanges(db);
            }

            if(oldVersion < 13){
                // 计划表增加“重复”列
                ScheduleTbl.getInstance().addColumnRepeat(db);
            }

        } else{ //降级 策略：清空表重建
            dropAllTbls(db);
            onCreate(db);
        }
    }

}
